<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>在线客服</title>
    <style>
        .body {
            width: 750px;
            margin: 0 auto;
        }

        .body .contact {
            width: 250px;
            height: 580px;
            float: left;
            position: relative;
            border: 1px solid green;
        }

        .body .contact .user {
            width: 250px;
            height: 40px;
            margin: 50px 10px 0px 10px;
        }

        .body .contact .footer {
            width: 250px;
            height: 40px;
            bottom: 0;
            position: absolute;
        }

        .body .container {
            width: 400px;
            height: 700px;
            float: left;
            padding: 0;
            border: 1px solid green;
        }

        .container .panel {
            width: 400px;
            height: 580px;
            background-color: #F5F5F5;
            overflow-x: hidden;
            overflow-y: scroll;
            border-bottom: 1px solid green;
        }

        .container .panel .item {
            width: 400px;
            margin-top: 10px;
            overflow-x: hidden;
            overflow-y: scroll;
        }

        .container .panel .item .title-left {
            width: 300px;
            float: left;
            font-size: 1px;
            text-align: left;
        }

        .container .panel .item .title-right {
            width: 300px;
            float: right;
            font-size: 1px;
            text-align: right;
        }

        .container .panel .item .content-left {
            width: 400px;
            float: left;
            text-align: left;
            white-space: normal;
            word-break: break-all;
            word-wrap: break-word;
            background-color: #FFFFFF;
        }

        .container .panel .item .content-right {
            width: 400px;
            float: right;
            text-align: right;
            white-space: normal;
            word-break: break-all;
            word-wrap: break-word;
            background-color: #FFFFFF;
        }

        .container .text {
            width: 400px;
            height: 46px;
            display: inline-block;
        }

        .container .text .left {
            width: 300px;
            height: 46px;
            float: left;
        }

        .container .text .left .input {
            width: 290px;
            height: 40px;
        }

        .container .text .right {
            width: 100px;
            height: 46px;
            float: left;
        }

        .container .text .right .button {
            width: 100px;
            height: 46px;
        }

        .container .opeate {
            width: 400px;
            height: 58px;
            padding: 10px 0;
            display: inline-block;
        }

        .container .opeate .item {
            width: 40px;
            height: 40px;
            float: left;
            margin: 0 19px;
            text-align: center;
            line-height: 40px;
            border: 1px solid #607d8b;
            border-radius: 5px;
        }
    </style>
</head>
<body>
<div class="body">
    <div class="container">
        <div class="panel" id="panel"></div>
        <div class="text">
            <div class="left">
                <input class="input" type="text" id="message"></input>
            </div>
            <div class="right">
                <button class="button" id="text">发送</button>
            </div>
        </div>
        <div class="opeate">
            <div class="item" id="emoji">表情</div>
            <div class="item" id="image">图片</div>
            <div class="item" id="file">文件</div>
            <div class="item" id="video">视频</div>
            <div class="item" id="voice">语音</div>
        </div>
    </div>
    <div class="contact">
        <div class="user">
            <lable for="pusherId">发送者：</lable>
            <input class="input" id="pusherId"></input>
        </div>
        <div class="user">
            <lable for="obtainId">接收者：</lable>
            <input class="input" id="obtainId"></input>
        </div>
        <button class="footer" onclick="initWebSocket()">打开聊天</button>
    </div>
</div>
</body>
<script>

    /**
     * 页面进行初始化
     */
    let socket;
    let panel = document.getElementById("panel");

    function initWebSocket() {
        let pusherId = document.getElementById('pusherId').value;
        if (pusherId) {
            bindClick();
            let ws = "ws://127.0.0.1:8081/online/" + pusherId;
            openSocket(ws, handler);
        }
    }

    /**
     * 绑定相关事件
     */
    function bindClick() {

        //发送按钮点击事件
        document.getElementById("text").addEventListener('click', function () {
            let message = document.getElementById('message').value;
            if (message) {
                let obtainId = document.getElementById('obtainId').value;
                let pusherId = document.getElementById('pusherId').value;
                let buffer = '{"obtainId":"' + obtainId + '","pusherId":"' + pusherId + '","message":"' + message + '","messageEnum":"direct" ,"messageType":"text"}';
                socket.send(buffer);
                document.getElementById('message').value = "";
                handler(JSON.parse(buffer), 1);
            }
        }, true)

        //表情按钮点击事件
        document.getElementById("emoji").addEventListener('click', function () {

        }, true)

        //图片按钮点击事件
        document.getElementById("image").addEventListener('click', function () {
            let obtainId = document.getElementById('obtainId').value;
            let pusherId = document.getElementById('pusherId').value;
            let fileId = "file-" + new Date().getTime();
            let child = document.createElement("input");
            child.type = 'file';
            child.id = fileId;
            child.accept = "image/*";
            child.style.display = "none";
            document.body.appendChild(child);
            let fileObject = document.getElementById(fileId);
            fileObject.addEventListener('click', function () {
            });
            fileObject.addEventListener('change', function () {
                let file = document.getElementById(fileId).files[0];
                let reader = new FileReader();
                //以base64形式读取文件
                reader.readAsDataURL(file);
                //文件读取完毕后该函数响应
                reader.onload = function loaded(event) {
                    let binaryString = event.target.result;
                    let buffer = '{"obtainId":"' + obtainId + '","pusherId":"' + pusherId + '","message":"' + binaryString + '","messageEnum":"direct" ,"messageType":"image"}';
                    socket.send(buffer);
                    document.body.removeChild(fileObject);
                    handler(JSON.parse(buffer), 1)
                }
            }, true);
            fileObject.click();
        }, true)

        //文件按钮点击事件
        document.getElementById("file").addEventListener('click', function () {
            let obtainId = document.getElementById('obtainId').value;
            let pusherId = document.getElementById('pusherId').value;
            let fileId = "file-" + new Date().getTime();
            let child = document.createElement("input");
            child.type = 'file';
            child.id = fileId;
            child.style.display = "none";
            document.body.appendChild(child);
            let fileObject = document.getElementById(fileId);
            fileObject.addEventListener('click', function () {
            });
            fileObject.addEventListener('change', function () {
                let file = document.getElementById(fileId).files[0];
                let reader = new FileReader();
                //以base64形式读取文件
                reader.readAsDataURL(file);
                //文件读取完毕后该函数响应
                reader.onload = function loaded(event) {
                    let binaryString = event.target.result;
                    let buffer = '{"obtainId":"' + obtainId + '","pusherId":"' + pusherId + '","message":"' + binaryString + '","messageEnum":"direct" ,"messageType":"file"}';
                    socket.send(buffer);
                    document.body.removeChild(fileObject);
                    handler(JSON.parse(buffer), 1)
                }
            }, true);
            fileObject.click();
        }, true)

        //视频按钮点击事件
        document.getElementById("video").addEventListener('click', function () {

        }, true)

        //语音按钮点击事件
        document.getElementById("voice").addEventListener('click', function () {

        }, true)
    }

    function createElement(title, position, _child) {

        let title_class;
        let title_show;
        let content_class;
        if (position === 0) {
            title_class = "title-left";
            content_class = "content-left";
            title_show = title + "   " + new Date().format("yyyy-MM-dd hh:mm:ss");
        }
        if (position === 1) {
            title_class = "title-right";
            content_class = "content-right";
            title_show = new Date().format("yyyy-MM-dd hh:mm:ss") + "   " + title;
        }
        let _title = document.createElement("lable");
        _title.classList.add(title_class);
        _title.innerText = title_show;

        let _content = document.createElement("div");
        _content.classList.add(content_class);

        let _item = document.createElement("div");
        _item.classList.add("item");

        panel.appendChild(_item);
        _item.appendChild(_title);
        _item.appendChild(_content);
        _content.appendChild(_child);
    }

    function handler(data, position) {
        if (data.messageType === 'text') {
            let p = document.createElement("p");
            p.innerText = data.message;
            createElement(data.pusherId, position, p)
        }
        if (data.messageType === 'file') {
            if (data.message.indexOf('data:image/png;') !== -1 || data.message.indexOf('data:image/jpeg;') !== -1) {
                let image = document.createElement("img");
                image.src = data.message;
                image.style.width = "100px";
                image.style.height = "100px";
                createElement(data.pusherId, position, image)
            } else {
                //判断是否是图片
                let file = document.createElement("a");
                file.href = data.message;
                file.innerText = "发送了一份文件，请点击查看";
                createElement(data.pusherId, position, file)
            }
        }
        if (data.messageType === 'image') {
            var image = document.createElement("img");
            image.src = data.message;
            image.style.width = "100px";
            image.style.height = "100px";
            createElement(data.pusherId, position, image)
        }
        if (data.messageType === 'emoji') {

        }
        if (data.messageType === 'video') {

        }
        if (data.messageType === 'voice') {

        }
    }

    function openSocket(ws, handler) {

        //检查服务
        if (typeof (WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
            return false;
        }

        //打开链接
        if (socket != null) {
            socket.close();
        }
        socket = new WebSocket(ws);

        //打开事件
        socket.onopen = function () {
            console.log("websocket已打开");
        };

        //消息事件
        socket.onmessage = function (message) {
            handler(JSON.parse(message.data), 0);
        };

        //关闭事件
        socket.onclose = function () {
            console.log("websocket已关闭");
        };

        //错误事件
        socket.onerror = function () {
            console.log("websocket发生了错误");
        }
    }

    Date.prototype.format = function (fmt) {
        let o = {
            "M+": this.getMonth() + 1,                     //月份
            "d+": this.getDate(),                          //日
            "h+": this.getHours(),                         //小时
            "m+": this.getMinutes(),                       //分
            "s+": this.getSeconds(),                       //秒
            "q+": Math.floor((this.getMonth() + 3) / 3),   //季度
            "S": this.getMilliseconds()                    //毫秒
        };
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (let k in o) {
            if (new RegExp("(" + k + ")").test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            }
        }
        return fmt;
    }
</script>
</html>